/**
 * @file 工单操作-完成
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer','element','form','laydate','upload','list_modify_common', '$http', 'QRCode', 'previewer'], function (exports) {
    var $ = layui.$;
    var element = layui.element;
    var form = layui.form;
    var laydate = layui.laydate;
    let upload = layui.upload;
    let timestamp = new Date().getTime();
    var opCommonUtils = layui.list_modify_common;
    var $http = layui.$http;

    var ALIPAY = 1;
    var WECHAT = 2;
    var BANK_TRANSFER = 5;

    //支付方式变量
    var PAY_TYPE_INTO = 11; // 系统转入
    var PAY_TYPE_QR = 1; // 扫码


    var returnData = {
        'payType': PAY_TYPE_QR,
        "orderId": $('input[name=orderId]').val(),
        "workId": $('input[name=workId]').val(),
        "channelId":$('input[name=channelId]').val(),
        "bizType":$('input[name=bizType]').val(),
        "casSign":$('#casSign').val()
    };


    /**
     * 给元素挂载日历
     * @param {string} ele 需要挂载日历的dom
     * */
    function calendar(ele) {
        laydate.render({
            elem:ele,
            type:"datetime",
            value:formatTime(),
            max:formatTime(),
        });
    };
    /**
     * 格式化时间函数;
     * retrun {string} 返回当前时间的 YYYY-MM-DD HH:MM:SS
     */
    function formatTime() {
        var now = new Date();
        var strContact =  "-";
        var strContactTime = ":";
        var year = now.getFullYear();
        var month = now.getMonth() > 8 ? now.getMonth() + 1:'0' + (now.getMonth() + 1);
        var day = now.getDate() > 9 ? now.getDate():"0" + now.getDate();
        var hour = now.getHours() > 9 ? now.getHours() : "0" + now.getHours();
        var minute = now.getMinutes() > 9 ? now.getMinutes() : "0" + now.getMinutes();
        var second = now.getSeconds() > 9 ? now.getSeconds() : "0" + now.getSeconds();
        return year + strContact + month + strContact + day + " " + hour + strContactTime + minute + strContactTime + second;
    };


    /**
     * 分转元
     * @returns {*}
     * @constructor
     * @param numstr
     */

    function Fen2Yuan(numstr) {
        Number.prototype.div = function (arg) {
            var t1 = 0, t2 = 0, r1, r2;
            try {
                t1 = this.toString().split(".")[1].length
            } catch (e) {
            }
            try {
                t2 = arg.toString().split(".")[1].length
            } catch (e) {
            }
            with (Math) {
                r1 = Number(this.toString().replace(".", ""));
                r2 = Number(arg.toString().replace(".", ""));
                return (r1 / r2) * pow(10, t2 - t1);
            }
        };
        var num = Number(numstr);
        return (num.div(100)).toFixed(2);
    }

    /**
     * 元转分
     * @param numstr
     * @returns {string}
     * @constructor
     */
    function Yuan2Fen(numstr) {
        var num = Number(numstr);
        return (num * 100).toFixed(0);
    }



    /**
     * 银行转账-点击保存
     */
    function save() {
        form.on('submit(save)',function (data) {
            var url = '/work/modify/complete/pay.action';
            var params ={};
            var certificateImgSrcList = [];

            Object.keys(data.field).forEach(function (key) {
                var value = data.field[key];
                if (key.includes('certificateImgSrc') && value) {
                    certificateImgSrcList.push(value);
                } else {
                    params[key] = value;
                }
            });

            if (certificateImgSrcList.length) {
                params.imageUrls = certificateImgSrcList.join(',');
            } else {
                layer.msg("请至少上传一张支付凭证");
                return false;
            }

            $http.lockSave(url, params, data.elem).then(function (data) {
                layer.msg(data.message || '操作成功', {icon: 1, time: 2000}, function () {
                    opCommonUtils.goOperateHome();
                });
            }, function (msg) {
                layer.msg(msg);
            });

            return false;
        })
    }
    /**
     * 验证表单规则
     */
    function verify() {
        form.verify({
            "non-empty":function (value) {
                if(!value){
                    return '内容不能为空'
                }
                if(value.length > 50){
                    return '不能超过50字'
                }
            }
        });
    }


    /**
     * 轮讯查询支付状态
     */
    function monitorPaymentStatus(paymentStatus) {
        var url = '/work/modify/save/complete.action';

        function requestPaymentStatus() {
            returnData["payChannelId"] = paymentStatus;

            $http.$save(url, returnData).then(function (data) {
                if (data.payStatus === 4) {
                    window.clearInterval(index);
                    layer.open({
                        content:data.message || '支付成功!正在为您跳转到工单详情',
                        time:2000,
                        end: opCommonUtils.goOperateHome()
                    });
                }
            });
        }

        index=window.setInterval(requestPaymentStatus, 1000);
    }
    
    function complete(btn) {
        var url = '/work/modify/termination/complete.action';
        $http.lockSave(url, returnData, btn).then(function (data) {
            layer.msg(data.message || '操作成功', {icon: 1, time: 2000}, function () {
                opCommonUtils.goOperateHome();
            });
        }, function (msg) {
            layer.msg(msg);
        });
    }


    /**
     * 在线支付二维码对话框
     * @param paymentMethod
     * @constructor
     */
    function QRdisplayDialog(paymentMethod) {
        var url = '/work/modify/complete/pay.action';

        returnData['payChannelId'] = paymentMethod;
        var index;
        $http.$save(url, returnData).then(function (data) {
            var url = data.qrCode;
            var popUpLayer = "<div id='payQRCode'></div>";

            layer.open({
                title: '付款二维码',
                type: 1,
                area: ['260px', '300px'], //宽高
                content: popUpLayer,
                success: function () {
                    //生成二维码
                    new QRCode(document.getElementById('payQRCode'), url);
                    //轮讯状态
                    monitorPaymentStatus(paymentMethod);
                },
                end: window.clearInterval(index)
            });
        }, function (msg) {
            layer.msg(msg);
        });
    }

    /**
     * 描述: 图片上传方法
     * @param elemId
     * @param valueId
     */
    let indexUploadImags;
    function uploaderImage(elemId, valueId) {
        upload.render({
            elem: '#' + elemId
            , exts: 'jpg|png|jpeg'
            , acceptMime: 'image/*'
            , accept: 'images'
            , url: '/work/modify/complete/uploaderImage.action?timestamp=' + timestamp + '&elemId=' + elemId
            , size: 5120
            , before: function (obj) {
                indexUploadImags = layui.layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            }
            , done: function (res) {
                if (res.status == 200) {
                    var data = res.data;
                    $("#" + valueId).val(data);
                    $("#" + elemId).attr("style", "background:url( " + data + "?"+Date.now()+");background-size:100% 100%;background-repeat:no-repeat;");
                    let next = $("#" + valueId).next();
                    let next1 = $(next).next();
                    $(next).attr("style", "visibility:hidden !important");
                    $(next1).attr("style", "visibility:hidden !important");
                    let prep = $("#" + valueId).prev();
                    prep.prop("src", data)
                } else {
                    layer.msg("上传失败！")
                }
                layui.layer.close(indexUploadImags);
            }
        });
    }

    /**
     * 初始化页面
     */
    function initPage() {
        calendar('#transferTime');
        $('#masterAmount').text(Fen2Yuan(orderWork.masterAmount));
        $('#totalAmount').text(Fen2Yuan(orderWork.totalAmount));
        $('#originalAmount').text(Fen2Yuan(orderWork.originalAmount));
        uploaderImage("certificateImgSrc", "certificateImgSrcValue");
        uploaderImage("certificateImgSrc2", "certificateImgSrc2Value");
        uploaderImage("certificateImgSrc3", "certificateImgSrc3Value");
    }
    
    
    /**
     * 初始化页面事件
     */
    function initEvent() {
        //银行转账-点击保存
        save();
        verify();

        //支付方式-点击弹出二维码
        $('#payment_method_alipay').on('click', function () {
            $('#bankTransferFragment').hide();
            new QRdisplayDialog(ALIPAY);
        });
        $('#payment_method_wechat').on('click', function () {
            $('#bankTransferFragment').hide();
            new QRdisplayDialog(WECHAT);
        });
        // 完成
        $('#payment_method_complete').on('click', function () {
            complete(this);
        });
        $('#payment_method_bank').on('click',function () {
            $('#bankTransferFragment').show();
        })
        // 点击删除图片
        $(document).on('click', '.btn-delete', function () {
            let $uploadDiv = $(this).parent().prev().prev();
            $uploadDiv.attr("style", "");
            $uploadDiv.find(".layui-upload-drag").attr("style", "");
            $uploadDiv.find("i").attr("style", "");
            $uploadDiv.find("p").attr("style", "");
            $uploadDiv.find(":hidden").val("");
            $uploadDiv.find("img").prop("src", "");
        });
        // 点击放大
        $(document).on('click', '.btn-review', function () {
            if (!$(this).parent().prev().prev().find("input").eq(0).val()) {
                layer.msg("请上传对应图片再预览");
                return;
            }
            let $container = $(this).parent().prev().prev().find("img").eq(0);
            $container.viewer().on('hide', function () {
                $container.viewer('destroy');
            });
            let index = $(this).index();
            $container.viewer('view', index);
        });

        // 监听银行卡下拉框选择
        form.on('select(transferCode)',function(data){
            var $option = $(data.elem).find('option[value="' + data.value + '"]');
            $('#toBank').val($option.data('name'));
            $('#companyName').val($option.data('value'));
        });
    }


    // 程序入口
    function init () {

      // 初始化页面
      initPage();

      // 初始化事件
      initEvent();
    }

    // 初始化
    init();

    exports('oms_work_modify_complete');
});
